<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../taglib.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>后台管理</title>
  <script type="text/javascript" src="js/SelectRoleWin.js?v=<%=Math.random()%>"></script>
  <style type="text/css">
  #rightCont{padding-top: 3px;}
  #sysResTree{margin-top: 10px;}
  </style>
 </head>
<body><rms:role operateCode="html_search">
	<div id="topTab" style="padding-bottom: 10px;"></div>
	
	<rms:role operateCode="opt_node">
       	<button id="btnAddRoot">添加根节点</button>
	</rms:role>
      	<br>
	<div class="sidebar-left" style="width: 260px;background: #fff;">
        <div id="sysResTree"></div>
    </div>
    <div class="sidebar-right">
    	<div id="rightTip" style="padding: 20px;"><h3>&lt;&lt; 点击菜单查看信息</h3></div>
		<div id="rightCont" style="display: none;width: 800px;">
			<fieldset>
		        <legend>基础信息</legend>
				<div class="result-content">
					<form id="baseForm">
						<input type="hidden" name="parentId" value="0">
						<input type="hidden" name="srId" value="0">
			            <table class="insert-tab">
			                <tr>
					            <th width="100"><s>*</s>资源名称:</th><td id="txtResName_">
					            <input name="resName"
						            msgId="resName_msg"
									rules="[
						  		     	{rule:{notNull:true},errorMsg:'资源名称不能为空'}
						  		     	,{rule:{maxLength:20},errorMsg:'资源名称长度不能超过20'}
						  		     ]"
									class="input-normal control-text" type="text" />
					            </td>
					            <td id="resName_msg"></td>
					        </tr>
			                <tr>
					            <th>URL:</th><td id="txtUrl_">
					            <input name="url"
						            msgId="url_msg"
									rules="[
						  		     	{rule:{maxLength:100},errorMsg:'URL长度不能超过100'}
						  		     ]"
									class="input-large control-text"/>
					            </td>
					            <td id="url_msg"></td>
					        </tr>
					        <rms:role operateCode="opt_node">
								<tr>
									<td></td>
									<td> <button id="btnSave" type="button" class="button button-primary">保存</button></td>
									<td></td>
								</tr>
							</rms:role>
			            </table>
		            </form>
	            </div>
			</fieldset>
			<br>
			<fieldset id="permPanel">
	          	<legend>操作权限</legend>
	          	<div class="search-content">
	          	<rms:role operateCode="addOpt">
		        	<table id="addOptForm" class="insert-tab">
						<tr><th width="100"><s>*</s>权限代码:</th><td id="txt-operateCode">
							<input name="operateCode" 
								msgId="operateCode_msg"
								rules="[
									{rule:{notNull:true},errorMsg:'权限代码不能为空'}
									,{rule:{maxLength:20},errorMsg:'权限代码长度不能超过20'}
								]"
								class="input-normal control-text" type="text" />
						</td>
						<td id="operateCode_msg"></td>
						</tr>
						<tr><th><s>*</s>权限名称:</th><td id="txt-operateName">
							<input name="operateName"
								msgId="operateName_msg"
								rules="[
									{rule:{notNull:true},errorMsg:'权限名称不能为空'}
									,{rule:{maxLength:20},errorMsg:'权限名称长度不能超过20'}
								]"
								class="input-normal control-text" type="text" />
						</td>
						<td id="operateName_msg"></td>
						</tr>
						<tr><th>URL:</th><td id="txt-url" colspan="2">
							<textarea style="width:300px;height: 70px;" placeholder="多个URL用逗号 , 隔开" name="url"
								class="control-row4 input-large"></textarea>
						</td>
						</tr>
						<tr>
							<td></td>
							<td> <button id="btnOptAdd" type="button" class="button button-primary">添加权限</button></td>
							<td></td>
						</tr>
		       		</table>
		       	</rms:role>
		       </div>
				<div class="result-content" style="padding-top: 10px;">
					<div class="grid-msg">
						btn_xx表示按钮权限;grid_xx表示表格按钮权限;html_xx表示页面权限
					</div>
					<div id="gridOpt"></div>
				</div>
			</fieldset>
		</div>
    </div>
    
    <div id="content" class="hide">
		<form id="J_Form" class="form-horizontal">
			<label><s>*</s>顶部菜单名称:</label>
			<input name="tabName"
				msgId="tabname-msg"
				rules="[
					{rule:{notNull:true},errorMsg:'不能为空'}
					,{rule:{maxLength:20},errorMsg:'长度不能超过20'}
				]"
				class="input-normal control-text" type="text" />
			<span id="tabname-msg" class="form-msg"></span>
			
		</form>
	</div>
	
	<div id="addNodeContent" class="hide">
		<form id="addNodeForm" class="form-horizontal">
			<input type="hidden" name="parentId" value="0">
			<table>
				<tr>
					<th><s>*</s>节点名称:</th>
					<td><input name="resName"
						msgId="resName-msg"
						rules="[
							{rule:{notNull:true},errorMsg:'不能为空'}
							,{rule:{maxLength:20},errorMsg:'长度不能超过20'}
						]"
				class="input-normal control-text" type="text" /></td>
					<td><span id="resName-msg" class="form-msg"></span></td>
				</tr>
				<tr>
					<th>URL:</th>
					<td><input name="url"
						msgId="nodeUrlmsg"
						rules="[
							{rule:{maxLength:200},errorMsg:'长度不能超过200'}
						]"
				class="input-large control-text"/></td>
					<td><span id="nodeUrlmsg" class="form-msg"></span></td>
				</tr>
			</table>
		</form>
	</div>

	<script type="text/javascript">
VUI.use(['PageForm','Tab','Tree','DialogForm'],function() {
	var listTopMenuUrl = ctx + 'listTopMenu.do';
	var listMenuUrl = ctx + 'listMenuByTabId.do';
	var addTopMenuUrl = ctx + 'addTopMenu.do';
	var addNodeUrl = ctx + 'addRSysRes.do';
	var delResUrl = ctx + 'delRSysRes.do';
	var updateResUrl = ctx + 'updateRSysRes.do';
	var addOptUrl = ctx + 'addSysFunction.do';
	var delOptUrl = ctx + 'delRSysFunction.do';
	var listOptUrl = ctx + 'listSysFunctionBySrId.do';
	var listRolePermissionSfIdUrl = ctx + 'listRolePermissionSfId_backuser.do';
	var addRolePermissionUrl = ctx + 'addRolePermission.do';
	var delRolePermissionUrl = ctx + 'delRolePermission.do';

	var tree;
	var tab;
	var treeStore;
	var gridStore;
	var topMenuDialog;
	var $addTabLi;
	var baseForm,addOptForm;
	
	var $rightTip = $('#rightTip');
	var $rightCont = $('#rightCont');
	var $permPanel = $('#permPanel');

	function init() {
		initTab();
 		initGrid();
 		initForm();
		initDialog();
	}

	function initTab() {
		Action.post(listTopMenuUrl,{},function(e){
			
			initTree();
			
			var rows = e;
			tab = new VUI.Tab({
				renderId:'topTab'
				,items:rows
				,border:false
				,loadFilter:function(items) {
					for(var i=0, len=items.length;i<len; i++) {
						items[i].title = items[i].tabName;
					}
				}
			});
			
			tab.on('Select',function(e){
				var item = e.item;
				console.log(e)
				console.log(tree)
				tree.load({tabId:item.id});
				
				$rightTip.show();
				$rightCont.hide();
			});
			
			tab.setNextDo(function(){
				this.select(0);
				appendNewTabBtn();
			})
			
		})
	}

	function initTree() {
		tree = new VUI.Tree({
			renderId:'sysResTree'
			,width:250
	       	,height: 350
			,url:listMenuUrl
			,initLoad:false
			,renderer:function(node) {
				var text = node.text;
				text += '&nbsp;' + buildTreeButton(node);

				return text;
			}
		});
		
		tree.on('Select',function(e) {
			var node = e.item;
			bindData(node);
		});
	}
	
	function initDialog() {
		topMenuDialog = new VUI.DialogForm({
			contentId:'content'
			,formId:'J_Form'
			,title:'添加顶部菜单'
            ,onOk:function() {
            	addTopMenu();
            }
		});
		
		addNodeDialog = new VUI.DialogForm({
			contentId:'addNodeContent'
			,formId:'addNodeForm'
			,width:400
			,onOk:function() {
				saveNode();
			}
		});
	}
	
	function initForm() {
		baseForm = new VUI.Form({formId:'baseForm'});
		addOptForm = new VUI.Form({formId:'addOptForm'});
	}
	
	function initGrid() {
      	grid = new VUI.Grid({
            renderId:'gridOpt'
            ,url:listOptUrl
            ,initLoad:false
            ,striped:true // 斑马线
           	,columns : [[
				{title:'权限代码',field:'operateCode'}
				, {title:'权限名称',field:'operateName'}
				, {title:'URL',field:'url',formatter:function(val,obj){
					   var urls = val.split(/\s*,\s*|\s*，\s*/);
					   var html = [];
					   for(var i=0,len=urls.length;i<len;i++) {
						   html.push(urls[i]);
					   }
					   html.sort();
					   return html.join('<br>');
				}}
				, {title:'操作',field:'',width:100,formatter : function(value,obj){
					 var updateStr = '<span class="grid-command btn-auth">授权</span>';
				     var delStr = '<span class="grid-command btn-del">删除</span>';
				     return RightUtil.auth('grid_auth',updateStr,'')  
				     	+ RightUtil.auth('grid_del',delStr,'');
				   }}
			]]
      	});
      	 //监听事件，删除一条记录
        grid.on('ClickCell',function(ev){
        	var sender = $(ev.target); //点击的Dom
        	if(sender.hasClass('btn-auth')){
            	var record = ev.row;
            	auth(record);
        	}
        	if(sender.hasClass('btn-del')){
            	var record = ev.row;
            	delOpt(record);
        	}
        });
	}
	
	
	function saveNode() {
    	addNodeDialog.submit({
    		url:addNodeUrl
    		,onSubmit:function(data) {
    			var r = this.validate();
    			if(r) {
    	    		var selectedTabItem = tab.getSelected();
    	    		data.tabId = selectedTabItem.id;
    			}
    			return r;
    		}
    		,success:function(result) {
    			Action.execResult(result,function(result){
					addNodeDialog.close();
					loadTree();
				});
    		}
    	});
	}
	
	function saveRes(){
		baseForm.submit({
			url:updateResUrl
			,onSubmit:function() {
				return this.check();
			}
			,success:function(result) {
				Action.execResult(result,function(result){
					loadTree();
					VUI.Msg.alert('提示','修改成功');
				});
			}
		});
	}
	
	function addOpt() {
		addOptForm.submit({
			url:addOptUrl
			,onSubmit:function(data) {
				var r = this.validate();
				if(r) {
					var sysRes = baseForm.getData();
					data.srId = sysRes.srId;
				}
				return r;
			}
			,success:function(result) {
				Action.execResult(result,function(result){
					grid.reload();
					addOptForm.reset();
				});
			}
		});
	}
	
	function bindData(node) {
		resetForm();
		
		baseForm.setData(node);
		
		grid.load({srId:node.id});
		
		$rightTip.hide();
		$rightCont.show();
		
		if(node.children && node.children.length > 0) {
			$permPanel.hide();
		}else{
			$permPanel.show();
		}
	}
	
	function resetForm() {
		// 清除错误并重置
		baseForm.reset();
		addOptForm.reset();
	}
	
	
	function appendNewTabBtn() {
		$addTabLi = $('<li class="vui-hover" style="border:0px;margin-left:5px;padding:5px;"><span style="margin:0px;" class="ui-icon ui-icon-plusthick" title="新建"></span></li>')
		
		$addTabLi.click(function(){
			topMenuDialog.reset(); //设置值，并且隐藏错误
			topMenuDialog.show();
		});
		
		appendLast($addTabLi);
	}
	
	function appendLast($addTabLi) {
		$addTabLi.appendTo($('#topTab').find('ul'));
	}
	
	function addTopMenu() {
		topMenuDialog.submit({
			url:addTopMenuUrl
			,onSubmit:function(data) {
				return topMenuDialog.check();
			}
			,success:function(data) {
				data.selected = true;
				tab.add(data);
				topMenuDialog.close();
			}
		});
	}
	
	function resetPanel() {
		$rightTip.show();
		$rightCont.hide();
	}

	function buildTreeButton(node) {
		var html = [];
		if(node.parentId == 0) {
			var addNodeStr = '<a onclick="'
				+ FunUtil.createFunStopProp(window, 'addChildNode', node)
				+ ' return false;">[添加子节点]</a>';
			
			html.push(RightUtil.auth('opt_node',addNodeStr,''));
		}
		if (node.children.length == 0) {
			var delNodeStr = '<a onclick="'
				+ FunUtil.createFunStopProp(window, 'delSysRes', node)
				+ ' return false;">[删除节点]</a>';
				
			html.push(RightUtil.auth('opt_node',delNodeStr,''));
		}
		return html.join('');
	}
	
	function addRootMenu(){
		addNodeDialog.setTitle('添加根节点');
		addNodeDialog.show();
		addNodeDialog.reset();
		addNodeDialog.setData({parentId:0});
	}

	window.addChildNode = function(node){
		addNodeDialog.show();
		addNodeDialog.setTitle('父节点:' + node.text);
		addNodeDialog.setData({parentId:node.id});
	}
	
	window.delSysRes = function(node){
		var self = this;
		if (node) {
			var msg = '确定要删除<strong>'+node.resName+'</strong>吗?';
			VUI.Msg.confirm('确认',msg,function(r){
				if(r) {
					Action.post(delResUrl,node,function(result){
						Action.execResult(result,function(result){
							resetPanel();
							loadTree();
						});
					});
				}
			});
		}
	}
	
	function delOpt(rowData) {
		var msg = '确定要删除<strong>'+rowData.operateName+'</strong>吗?';
		VUI.Msg.confirm('确认',msg,function(r){
			if(r) {
				doDelOpt(rowData);
			}
		});
	}
	
	function doDelOpt(row){
		Action.post(delOptUrl,row,function(result){
			Action.execResult(result,function(result){
				grid.reload();
			});
		});
	}
	
	function loadTree() {
		tree.reload();
	}
	
	$('#btnAddRoot').click(function(){
		addRootMenu();
	});
	
	$('#btnSave').click(function(){
		saveRes();
	});
	$('#btnOptAdd').click(function(){
		addOpt();
	});
	
	/// 
	
	
	var roleHandlers = {
		selectHandler:function(item){
			addSysFunRole(item);
		}
	  	,unselectHandler:function(item){
	  		delSysFunRole(item);
	  	}
	}
	
	function addSysFunRole(item) {
		item.url = addRolePermissionUrl;
		setRolePermission(item);
	}
	
	function delSysFunRole(item) {
		item.url = delRolePermissionUrl;
		setRolePermission(item);
	}
	
	function setRolePermission(param) {
		var url = param.url;
		
		var data = {
			sfId:param.extKey
			,roleId:param.roleId
		}
		
		Action.post(url,data,function(e){
			Action.execResult(e,function(){
				grid.reload();
			});
		});
	}
	  	
	// 资源管理授权功能
	function auth(rowData) {
		var sfId = rowData.sfId;
		Action.post(listRolePermissionSfIdUrl,{sfId:sfId},function(rolePerms){
			var roleIds = [];
			for(var i=0,len=rolePerms.length; i<len; i++) {
				roleIds.push(rolePerms[i].roleId);
			}
			
			SelectRoleWin.show(roleIds,sfId,roleHandlers);
		});
	}

	init();
});
</script>
</rms:role>
</body>
</html>
